#!/usr/bin/env python3
"""
模型切换工具

提供命令行界面，方便用户切换不同的大模型API。
"""

import sys
import yaml
from pathlib import Path
from typing import Dict, Any


def load_config() -> Dict[str, Any]:
    """加载配置文件"""
    config_path = Path(__file__).parent / "config.yaml"
    if not config_path.exists():
        raise FileNotFoundError(f"配置文件不存在: {config_path}")
    
    with open(config_path, 'r', encoding='utf-8') as f:
        return yaml.safe_load(f)


def save_config(config: Dict[str, Any]) -> None:
    """保存配置文件"""
    config_path = Path(__file__).parent / "config.yaml"
    with open(config_path, 'w', encoding='utf-8') as f:
        yaml.dump(config, f, allow_unicode=True, default_flow_style=False)
    print("配置文件已更新")


def list_models():
    """列出所有可用模型"""
    config = load_config()
    models = config.get('vision_models', {})
    
    print("\n可用模型:")
    print("-" * 50)
    for key, model in models.items():
        status = "✓" if validate_model_config(model) else "✗"
        print(f"{status} {key:<20} - {model.get('name', key)}")
        print(f"  描述: {model.get('description', '无描述')}")
        print(f"  模型: {model.get('model', '未知')}")
        print()


def validate_model_config(model: Dict[str, Any]) -> bool:
    """验证模型配置是否完整"""
    required_keys = ['api_key', 'base_url', 'model']
    return all(key in model and model[key] for key in required_keys)


def switch_model(model_name: str):
    """切换到指定模型"""
    config = load_config()
    models = config.get('vision_models', {})
    
    if model_name not in models:
        print(f"错误: 模型 '{model_name}' 不存在")
        list_models()
        return
    
    old_model = config.get('default_model', '')
    config['default_model'] = model_name
    save_config(config)
    
    print(f"已切换模型: {old_model} → {model_name}")
    
    model = models[model_name]
    if not validate_model_config(model):
        print(f"警告: 模型 '{model_name}' 配置不完整，请检查config.yaml")


def show_current():
    """显示当前使用的模型"""
    config = load_config()
    current = config.get('default_model', '未设置')
    models = config.get('vision_models', {})
    
    if current in models:
        model = models[current]
        print(f"当前模型: {current}")
        print(f"名称: {model.get('name', current)}")
        print(f"描述: {model.get('description', '无描述')}")
        
        if not validate_model_config(model):
            print("状态: 配置不完整，需要设置API密钥")
        else:
            print("状态: 配置完整")
    else:
        print(f"当前模型: {current} (不存在)")


def main():
    """主函数"""
    if len(sys.argv) < 2:
        print("使用方法:")
        print("  python switch_model.py list          - 列出所有模型")
        print("  python switch_model.py show           - 显示当前模型")
        print("  python switch_model.py switch <模型名> - 切换模型")
        print("\n示例:")
        print("  python switch_model.py switch openai_gpt4")
        print("  python switch_model.py switch anthropic_claude")
        return
    
    command = sys.argv[1].lower()
    
    if command == 'list':
        list_models()
    elif command == 'show':
        show_current()
    elif command == 'switch':
        if len(sys.argv) < 3:
            print("错误: 请指定模型名称")
            list_models()
            return
        switch_model(sys.argv[2])
    else:
        print(f"未知命令: {command}")
        print("使用 'python switch_model.py' 查看帮助")


if __name__ == '__main__':
    main()